using Godot;
using System;
using System.Collections.Generic;

public partial class RobotWeaponSelection : Node2D
{
    [Signal]
    public delegate void OnSelectWeaponEventHandler(WeaponEntity weapon);
    CanvasLayer canvasLayer;
    Control root;
    Control weaponRoot;
    List<WeaponSelectionItem> weaponItems = new();
    Button buttonBack;

    void GetChildComponents()
    {
        canvasLayer = GetNode<CanvasLayer>("CanvasLayer");
        root = GetNode<Control>("CanvasLayer/UIRoot");
        weaponRoot = GetNode<Control>("CanvasLayer/UIRoot/P/V/MB/H");
        foreach (var child in weaponRoot.GetChildren())
        {
            if (child is WeaponSelectionItem weaponItem)
            {
                weaponItems.Add(weaponItem);
                weaponItem.OnSelect += OnWeaponItemSelectHandler;
            }
        }
        buttonBack = GetNode<Button>("%ButtonBack");
        buttonBack.Pressed += OnButtonBackPressedHandler;
    }

    private void OnButtonBackPressedHandler()
    {
        AnimateHide();
    }


    private void OnWeaponItemSelectHandler(WeaponEntity weapon)
    {
        AnimateHide();
        EmitSignal(SignalName.OnSelectWeapon, weapon);
    }


    public override void _Ready()
    {
        base._Ready();
        GetChildComponents();
    }

    Vector2 startPos = new Vector2(0, 648);
    Vector2 endPos = new Vector2(0, 0);
    Tween tween;
    // List<WeaponEntity> weaponList;

    public void AnimateShow(List<WeaponEntity> list)
    {
        GameManager.Instance.LockInput();
        // weaponList = list;
        tween?.Stop();
        tween = CreateTween();
        tween.TweenProperty(root, "position", endPos, 0.2f);
        tween.Finished += OnTweenFinishedHandler;
        for (int i = 0; i < weaponItems.Count; i++)
        {
            if (list.Count > i)
            {
                weaponItems[i].SetInfo(list[i]);
                weaponItems[i].Show();
            }
            else
            {
                weaponItems[i].Hide();
            }
        }
    }

    public void AnimateHide()
    {
        GameManager.Instance.LockInput();
        tween?.Stop();
        tween = CreateTween();
        tween.TweenProperty(root, "position", startPos, 0.2f);
        tween.Finished += OnTweenFinishedHandler;
    }

    private void OnTweenFinishedHandler()
    {
        GameManager.Instance.AllowInput();
    }

}
